/* Copyright 2012 Oliver Katz

    This file is part of Theta.

    Theta is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include "report.h"

namespace vm
{
	namespace report
	{
		void Report::prefix(string r)
		{
			time_t t = time(NULL);
			struct tm tm = *localtime(&t);
			stringstream ss;
			ss << "[" << r << "@" << tm.tm_mon << "/" << tm.tm_mday << "/" << tm.tm_year << "-" << tm.tm_hour << ":" << tm.tm_min << ":" << tm.tm_sec << "] ";
			content = ss.str();
		}

		Report::Report()
		{
		}

		Report::Report(string r, string m)
		{
			prefix(r);
			stringstream ss;
			ss << m << "\n";
			content += ss.str();
		}

		Report::Report(string r, string n, string v)
		{
			prefix(r);
			stringstream ss;
			ss << n << " <= \"" << v << "\"\n";
			content += ss.str();
		}

		Report::Report(string r, string n, int v)
		{
			prefix(r);
			stringstream ss;
			ss << n << " <= " << v << "\n";
			content += ss.str();
		}

		Report::Report(string r, string n, float v)
		{
			prefix(r);
			stringstream ss;
			ss << n << " <= " << v << "\n";
			content += ss.str();
		}

		string Report::toString()
		{
			return content;
		}

		int Reporter::getPID()
		{
			return (int)getpid();
		}

		Reporter::Reporter(string n)
		{
			name = n;
			pid = getPID();
		}

		void Reporter::pushReport(Report r)
		{
			string buf = r.toString();
			
			DIR *d = opendir("/tmp/theta");
			if (d != NULL)
			{
				closedir(d);
			}
			else
			{
				mkdir("/tmp/theta", S_IRWXU);
			}

			stringstream path;
			path << "/tmp/theta/" << pid << ".reporter";
			ifstream f(path.str().c_str());
			if (!f)
			{
				if (mkfifo(path.str().c_str(), S_IRWXU) != 0)
				{
					cerr << "error: cannot create " << path.str() << "\n";
					_exit(1);
				}
			}

			int p = open(path.str().c_str(), O_WRONLY);
			write(p, buf.c_str(), strlen(buf.c_str()));
			close(p);
		}

		void Reporter::popReportStream()
		{
			stringstream path;
			path << "/tmp/theta/" << pid << ".reporter";
			int p = open(path.str().c_str(), O_RDONLY);
			if (p < 0)
				return ;
			char buf;
			while (1)
			{
				read(p, &buf, sizeof(char));
				cout << p;
			}
			close(p);
		}
	}
}